using Bogus;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using OData.Shared.Models;

namespace OData.Data
{
    public static class FakeDataSeedingExtension
    {
        public static void MakeSureDbCreated(this WebApplication app)
        {
            using var scope = app.Services.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

            // 创建Faker实例
            var addressFaker = new Faker<Address>()
                .RuleFor(a => a.Street, f => f.Address.StreetAddress())
                .RuleFor(a => a.City, f => f.Address.City())
                .RuleFor(a => a.State, f => f.Address.State())
                .RuleFor(a => a.ZipCode, f => f.Address.ZipCode());

            var lineItemFaker = new Faker<LineItem>()
                .RuleFor(l => l.Id, f => f.UniqueIndex)
                .RuleFor(l => l.Number, f => f.Random.Int(1, 100))
                .RuleFor(l => l.Description, f => f.Commerce.ProductName())
                .RuleFor(l => l.Quantity, f => f.Random.Int(1, 10))
                .RuleFor(l => l.UnitPrice, f => f.Random.Decimal(10, 100))
                .RuleFor(l => l.Fulfilled, f => f.Random.Bool());

            var orderFaker = new Faker<Order>()
                .RuleFor(o => o.Id, f => f.UniqueIndex)
                .RuleFor(o => o.Amount, f => f.Random.Decimal(100, 1000))
                .RuleFor(o => o.LineItems, f => lineItemFaker.Generate(f.Random.Int(1, 5)));

            var customerFaker = new Faker<Customer>()
                .RuleFor(c => c.Id, f => f.UniqueIndex)
                .RuleFor(c => c.Name, f => f.Name.FullName())
                .RuleFor(c => c.HomeAddress, f => addressFaker.Generate())
                .RuleFor(c => c.Orders, f => orderFaker.Generate(f.Random.Int(1, 3)));

            // 生成模拟数据并添加到数据库
            var customers = customerFaker.Generate(10); // 生成10个客户
            dbContext.Customers.AddRange(customers);
            dbContext.SaveChanges();
        }
    }
}
